package com.blue.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.blue.gateway.config.AuthConfig;
import com.litblue.common.exception.BizIllegalException;
import com.litblue.starter.cache.redis.RedisCache;
import com.litblue.starter.cache.redis.RedisKeys;
import com.litblue.starter.core.AjaxResult;
import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;


@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {

    private final AuthConfig authConfig;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private RedisCache redisCache;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if (checkPath(request.getPath().toString())){
            return chain.filter(exchange);
        }
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("Authorization");
        if (StrUtil.isEmpty(token)){
           return handleUnauthorized(response);
        }
        Object userId = redisCache.getCacheObject(RedisKeys.DEFINE_TOKEN + token);
        if (userId==null){
            return handleUnauthorized(response);

        }
        ServerWebExchange webExchange = exchange.mutate().request(builder ->
           builder.header("user-info",userId.toString())
        ).build();

        return chain.filter(webExchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
    private boolean checkPath(String path) {
        for (String excludePath : authConfig.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }
    private Mono<Void> handleUnauthorized(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        AjaxResult ajaxResult = new AjaxResult<>("鉴权失败","401");
        String body = JSON.toJSONString(ajaxResult);
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }
}
